<!DOCTYPE html>
<html lang="zh-cmn-Hans" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <link rel="shortcut icon" href="favicon.ico">
    <link rel="stylesheet" href="css/iconfont.css">
    <link rel="stylesheet" href="css/global.css">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="css/swiper.min.css">
    <link rel="stylesheet" href="css/styles.css">
    <script src="js/jquery.1.12.4.min.js" charset="UTF-8"></script>
    <script src="js/bootstrap.min.js" charset="UTF-8"></script>
    <script src="js/swiper.min.js" charset="UTF-8"></script>
    <script src="js/global.js" charset="UTF-8"></script>
    <script src="js/jquery.DJMask.2.1.1.js" charset="UTF-8"></script>
    <title>农资商贸销售系统</title>
</head>
<body>

<!-- 顶部tab -->
<div th:replace="~{mall/common :: header}"></div>

<!-- 搜索栏 -->
<div th:replace="~{mall/common :: topSearch}"></div>

<div class="content clearfix bgf5">
    <section class="user-center inner clearfix">
        <div class="user-content__box clearfix bgf">
            <div class="title">购物车</div>
            <form class="shopcart-form__box">
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th width="150">
                            <label class="checked-label"><input type="checkbox" class="check-all"><i></i> 全选</label>
                        </th>
                        <th width="300">商品信息</th>
                        <th width="150">单价</th>
                        <th width="200">数量</th>
                        <th width="200">合计</th>
                        <th width="80">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr th:each="cart : ${shoppcartList}" th:data-id="${cart.id}">
                        <th scope="row">
                            <label class="checked-label"><input type="checkbox"><i></i>
                                <div class="img"><img th:src="${cart.img}" th:alt="${cart.title}" class="cover"></div>
                            </label>
                        </th>
                        <td>
                            <div class="goodis-id" style="display: none;" th:text="${cart.goodsid}"></div>
                            <div class="name ep3" th:text="${cart.title}"></div>
                            <div class="type c9" th:text="${cart.describe}"></div>
                        </td>
                        <td th:text="${'¥'+cart.price}"></td>
                        <td>
                            <div class="cart-num__box">
                                <input type="button" class="sub" value="-">
                                <input type="number" class="val" th:value="${cart.num}" th:max="${cart.stock}"
                                       th:maxlength="2">
                                <input type="button" class="add" value="+">
                            </div>
                        </td>
                        <td th:text="${'¥'+cart.price * cart.num}">¥</td>
                        <td><a onclick="deleteCart(this)">删除</a></td>
                    </tr>
                    </tbody>
                </table>
                <div class="user-form-group tags-box shopcart-submit pull-right">
                    <button type="button" onclick="submitOrder()" class="btn">提交订单</button>
                </div>
                <div class="checkbox shopcart-total">
                    <label><input type="checkbox" class="check-all"><i></i> 全选</label>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onclick="deleteCart(this)">删除</a>
                    <div class="pull-right">
                        已选商品 <span>2</span> 件
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;合计（不含运费）
                        <b class="cr">¥<span class="fz24">40.00</span></b>
                    </div>
                </div>
                <script>

                    function submitOrder(){
                        //获取选中的数据
                        let selectedItems = $('.shopcart-form__box tbody input[type="checkbox"]:checked');
                        if(selectedItems.length === 0){
                            alert("请先选中数据");
                            return false;
                        }else{
                            let data = [];
                            selectedItems.each(function(){
                                let tr = $(this).closest('tr');
                                let item = {
                                    cartId: tr.attr('data-id'),
                                    goodsId: tr.find('.goodis-id').text(),
                                    title: tr.find('.name').text(),
                                    num: tr.find('.val').val(),
                                    price: tr.find('td:nth-child(3)').text().slice(1),
                                    total: tr.find('td:nth-child(5)').text().slice(1)
                                };
                                data.push(item);
                            });

                            //发起请求提交订单
                            $.ajax({
                                url: 'order/submitOrder',
                                type: 'POST',
                                data: JSON.stringify(data),
                                contentType: "application/json",
                                success: function (res) {
                                    if (res.code === 200) {
                                        window.location.href = '/mall/userCartPay?id='+res.data
                                    }else  if (res.code === 401){
                                        DJMask.open({
                                            width: "300px",
                                            height: "100px",
                                            content: res.msg+"，将在三秒后自动跳转到登录页面"
                                        })
                                        //倒计时三秒跳转到登录页面
                                        setTimeout(function () {
                                            window.location.href="/mall/login";
                                        }, 3000);
                                    }else{
                                        DJMask.open({
                                            width: "300px",
                                            height: "100px",
                                            content: res.msg
                                        })
                                    }
                                },
                                error: function () {
                                    alert("服务器异常");
                                }
                            });
                        }
                    }


                    function deleteCart(obj) {
                        var tr = $(obj).parents('tr');
                        let isRow = tr.length;
                        let ids = [];
                        //判断是全选还是行删除
                        if (isRow > 0) {
                            ids.push(tr.data('id'));
                        }else{
                            $('.shopcart-form__box tbody input[type="checkbox"]:checked').each(function() {
                                ids.push( $(this).parents('tr').data('id'));
                            });
                        }
                        $.ajax({
                            url: 'cart/deletes',
                            type: 'POST',
                            data: {ids: ids},
                            success: function (res) {
                                if (res.code === 200) {
                                    if (isRow > 0) {
                                        tr.remove();
                                    }else{
                                        $('.shopcart-form__box tbody input[type="checkbox"]:checked').each(function() {
                                            $(this).parents('tr').remove();
                                        });
                                    }
                                    computeSelected();
                                }else if (res.code === 401) {
                                    DJMask.open({
                                        width: "300px",
                                        height: "100px",
                                        content: res.msg + "，将在三秒后自动跳转到登录页面"
                                    })
                                    //倒计时三秒跳转到登录页面
                                    setTimeout(function () {
                                        window.location.href = "/mall/login";
                                    }, 3000);
                                } else {
                                    DJMask.open({
                                        width: "300px",
                                        height: "100px",
                                        content: res.msg
                                    })
                                }
                            },
                            error: function () {
                                alert('删除失败,网络繁忙请稍后再试！！！')
                            }
                        })
                    }

                    // 计算已选商品的数量和金额
                    function computeSelected() {
                        var quantity = 0;
                        var total = 0;
                        $('.shopcart-form__box tbody input[type="checkbox"]:checked').each(function () {
                            var tr = $(this).parents('tr');
                            quantity += parseInt(tr.find('.val').val()); // 获取数量
                            total += parseFloat(tr.find('td:nth-child(5)').text().slice(1)); // 获取金额
                        });

                        // 更新已选商品数量和金额
                        $('.shopcart-total span').text(quantity);
                        $('.shopcart-total .fz24').text(total.toFixed(2));
                    }

                    $(document).ready(function () {
                        var $item_checkboxs = $('.shopcart-form__box tbody input[type="checkbox"]'),
                            $check_all = $('.check-all');
                        // 全选
                        $check_all.on('change', function () {
                            $check_all.prop('checked', $(this).prop('checked'));
                            $item_checkboxs.prop('checked', $(this).prop('checked'));
                            computeSelected();
                        });
                        // 点击选择
                        $item_checkboxs.on('change', function () {
                            var flag = true;
                            $item_checkboxs.each(function () {
                                if (!$(this).prop('checked')) {
                                    flag = false
                                }
                            });
                            $check_all.prop('checked', flag);
                        });

                        // checkbox change事件
                        $('.shopcart-form__box tbody input[type="checkbox"]').change(computeSelected);

                        // 计算初始选中的商品数量和金额（如果有）
                        computeSelected();
                        // 个数限制输入数字
                        $('input.val').onlyReg({reg: /[^0-9.]/g});

                        // 加减个数
                        $('.cart-num__box').on('click', '.sub,.add', function () {
                            var value = parseInt($(this).siblings('.val').val());
                            var price = parseFloat($(this).parents('tr').children('td:nth-child(3)').text().slice(1)); // 获取单价
                            if ($(this).hasClass('add')) {
                                if (value < 99) {
                                    $(this).siblings('.val').val(Math.min((value += 1), 99));
                                }
                            } else {
                                if (value !== 1) {
                                    $(this).siblings('.val').val(Math.max((value -= 1), 1));
                                }
                            }
                            $(this).parents('tr').children('td:nth-child(5)').text('¥' + (value * price).toFixed(2)); // 更新合计
                            computeSelected();
                        });

                        // 监听数量输入
                        $('.cart-num__box .val').on('change', function () {
                            var quantity = parseInt($(this).val());
                            var price = parseFloat($(this).parents('tr').children('td:nth-child(3)').text().slice(1)); // 获取单价
                            $(this).parents('tr').children('td:nth-child(5)').text('¥' + (quantity * price).toFixed(2)); // 更新合计
                            if (quantity <= 0) {
                                alert("数量不能为0");
                                $(this).val(1);
                                $(this).parents('tr').children('td:nth-child(5)').text('¥' + price.toFixed(2)); // 更新合计
                            }
                            computeSelected();
                        });

                    });
                </script>
            </form>
        </div>
    </section>
</div>

<!-- 右侧菜单 -->
<div th:replace="~{mall/common :: rightNav}"></div>
<!-- 底部信息 -->
<div th:replace="~{mall/common :: footer}"></div>
</body>
</html>